#include"chatserver.hpp"
#include"chatservice.hpp"

// 初始化聊天服务器对象
ChatServer::ChatServer(EventLoop *loop,
                       const InetAddress &listenAddr,
                       const string &nameArg)
    : _server(loop, listenAddr, nameArg), _loop(loop)
{
    // 注册链接回调
    //_server.setConnectionCallback(onConnection);
    _server.setConnectionCallback(std::bind(&ChatServer::onConnection, this, _1));

    // 注册消息回调
    //_server.setMessageCallback(onMessage);
    _server.setMessageCallback(std::bind(&ChatServer::onMessage, this, _1, _2, _3));

    // 设置线程数量
    _server.setThreadNum(4);
}

// 启动服务
void ChatServer::start()
{
    _server.start();
}

void ChatServer::onConnection(const TcpConnectionPtr &conn)
{
    if(conn->connected())
    {
        cout<<"连接成功"<<endl;
    }
    else
    {
        //如果客户端异常关闭
        Chatservice::instance()->clientCloseException(conn);
        cout<<"断开连接"<<endl;
        conn->shutdown();
    }
}


void ChatServer::onMessage(const TcpConnectionPtr &conn,
                           Buffer *buffer,
                           Timestamp time)
//回响服务器
{
    string message=buffer->retrieveAllAsString();

    cout<<"message: "<<message<<endl;
    Json::Reader reader;
    Json::Value value;
    reader.parse(message,value);
    int msgid=value["msgid"].asInt();
    cout<<"msgid: "<<msgid<<endl;
    //获取回调函数
    auto msgHandler=Chatservice::instance()->getHandler(msgid);
    msgHandler(conn,value,time);
}




